import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'

export const useUserStore = defineStore('user', () => {
  // 状态
  const user = ref(null)
  const loading = ref(false)
  const error = ref(null)

  // 计算属性
  const isLoggedIn = computed(() => !!user.value)
  const userProfile = computed(() => user.value || {})

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  // 检查认证状态
  const checkAuthStatus = async () => {
    const token = localStorage.getItem('token')
    if (token) {
      try {
        loading.value = true
        const response = await api.get('/users/profile')
        user.value = response.data.user
      } catch (err) {
        console.error('检查认证状态失败:', err)
        localStorage.removeItem('token')
        user.value = null
      } finally {
        loading.value = false
      }
    }
  }

  // 登录
  const login = async (credentials) => {
    try {
      loading.value = true
      error.value = null
      
      const response = await api.post('/auth/login', credentials)
      
      if (response.data.success) {
        user.value = response.data.user
        localStorage.setItem('token', response.data.token)
        return { success: true }
      } else {
        throw new Error(response.data.message || '登录失败')
      }
    } catch (err) {
      error.value = err.response?.data?.message || err.message || '登录失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  // 更新用户信息
  const updateProfile = async (profileData) => {
    try {
      loading.value = true
      error.value = null

      const response = await api.put('/users/profile', profileData)
      
      if (response.data.success) {
        user.value = { ...user.value, ...response.data.user }
        return { success: true, message: '个人信息更新成功' }
      } else {
        throw new Error(response.data.message || '更新失败')
      }
    } catch (err) {
      error.value = err.response?.data?.message || err.message || '更新失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  // 上传头像
  const uploadAvatar = async (file) => {
    try {
      loading.value = true
      error.value = null

      const formData = new FormData()
      formData.append('avatar', file)

      const response = await api.post('/users/avatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (response.data.success) {
        user.value = { ...user.value, avatar: response.data.avatarUrl }
        return { success: true, message: '头像更新成功' }
      } else {
        throw new Error(response.data.message || '头像上传失败')
      }
    } catch (err) {
      error.value = err.response?.data?.message || err.message || '头像上传失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePassword = async (passwordData) => {
    try {
      loading.value = true
      error.value = null

      const response = await api.put('/users/password', passwordData)
      
      if (response.data.success) {
        return { success: true, message: '密码修改成功' }
      } else {
        throw new Error(response.data.message || '密码修改失败')
      }
    } catch (err) {
      error.value = err.response?.data?.message || err.message || '密码修改失败'
      return { success: false, error: error.value }
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const logout = () => {
    user.value = null
    localStorage.removeItem('token')
  }

  return {
    // 状态
    user,
    loading,
    error,
    // 计算属性
    isLoggedIn,
    userProfile,
    // 方法
    clearError,
    checkAuthStatus,
    login,
    updateProfile,
    uploadAvatar,
    changePassword,
    logout
  }
}) 